<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>MySQL主从复制（Replication） | J.のblog</title><meta name="keywords" content="mysql"><meta name="author" content="J."><meta name="copyright" content="J."><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="一、主从复制1.主从复制介绍两台MySQL实例，通过binlog  自动 “实时” 同步数据通常可以用作：辅助备份+ 架构演变 2.主从复制搭建 两台以上MySQL实例（server_id不同，port，socket等），确认主从身份  mysql&gt; select @@server_id;   主库开启二进制（binlog）日志  mysql&gt; select @@log_bin;">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL主从复制（Replication）">
<meta property="og:url" content="http://dycloudnavite.love/2019/03/23/MySQL%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%EF%BC%88Replication%EF%BC%89/index.html">
<meta property="og:site_name" content="J.のblog">
<meta property="og:description" content="一、主从复制1.主从复制介绍两台MySQL实例，通过binlog  自动 “实时” 同步数据通常可以用作：辅助备份+ 架构演变 2.主从复制搭建 两台以上MySQL实例（server_id不同，port，socket等），确认主从身份  mysql&gt; select @@server_id;   主库开启二进制（binlog）日志  mysql&gt; select @@log_bin;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://dycloudnavite.love/img/mysql.jpg">
<meta property="article:published_time" content="2019-03-23T08:42:00.000Z">
<meta property="article:modified_time" content="2022-09-02T10:00:35.887Z">
<meta property="article:author" content="J.">
<meta property="article:tag" content="mysql">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://dycloudnavite.love/img/mysql.jpg"><link rel="shortcut icon" href="/dujie5416/img/touxiang.png"><link rel="canonical" href="http://dycloudnavite.love/2019/03/23/MySQL%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%EF%BC%88Replication%EF%BC%89/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/dujie5416/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/dujie5416/',
  algolia: {"appId":"9GWB2VV7GN","apiKey":"dac56ec5b0b1f45281251ee59db4d637","indexName":"blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'MySQL主从复制（Replication）',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-09-02 18:00:35'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/xxx.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/tzy13755126023/BLOG_SOURCE/css/function.min.css"><link rel="stylesheet" href="/css/rightMenu.css"><style type="text/css">#toggle-sidebar {left:100px}</style><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/dujie5416/atom.xml" title="J.のblog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/dujie5416/img/touxiang.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/dujie5416/img/longzhu.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/dujie5416/">J.のblog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">MySQL主从复制（Replication）</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-03-23T08:42:00.000Z" title="发表于 2019-03-23 16:42:00">2019-03-23</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-09-02T10:00:35.887Z" title="更新于 2022-09-02 18:00:35">2022-09-02</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/dujie5416/categories/mysql/">mysql</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="MySQL主从复制（Replication）"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="一、主从复制"><a href="#一、主从复制" class="headerlink" title="一、主从复制"></a>一、主从复制</h1><h5 id="1-主从复制介绍"><a href="#1-主从复制介绍" class="headerlink" title="1.主从复制介绍"></a>1.主从复制介绍</h5><p>两台MySQL实例，通过binlog  自动 “实时” 同步数据<br>通常可以用作：辅助备份+ 架构演变</p>
<h5 id="2-主从复制搭建"><a href="#2-主从复制搭建" class="headerlink" title="2.主从复制搭建"></a>2.主从复制搭建</h5><ul>
<li>两台以上MySQL实例（server_id不同，port，socket等），确认主从身份</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; select @@server_id;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>主库开启二进制（binlog）日志</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; select @@log_bin;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<ul>
<li>主库开启复制专用用户：replication slave</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; grant replication slave on *.* to repl@&#39;10.0.0.5%&#39; identified by &#39;123&#39;;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>


<ul>
<li>主库备份恢复到从库</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">mysqldump -uroot -p456 -S &#x2F;data&#x2F;3307&#x2F;mysql.sock -A --master-data&#x3D;2 --single-transaction &gt;&#x2F;tmp&#x2F;full.sql
mysql -S &#x2F;data&#x2F;3308&#x2F;mysql.sock
mysql&gt; set sql_log_bin&#x3D;0;
mysql&gt; source &#x2F;tmp&#x2F;full.sql<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li>告诉从库复制相关信息：change master to  ，IP，port user  password    file_name  position<ul>
<li>起点：</li>
</ul>
</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">vim &#x2F;tmp&#x2F;full.sql
-- CHANGE MASTER TO MASTER_LOG_FILE&#x3D;&#39;mysql-bin.000002&#39;, MASTER_LOG_POS&#x3D;444;
mysql&gt; change master to;
CHANGE MASTER TO
  MASTER_HOST&#x3D;&#39;10.0.0.62&#39;,
  MASTER_USER&#x3D;&#39;repl&#39;,
  MASTER_PASSWORD&#x3D;&#39;123456&#39;,
  MASTER_PORT&#x3D;3307,
  MASTER_LOG_FILE&#x3D;&#39;mysql-bin.000002&#39;,
  MASTER_LOG_POS&#x3D;444,
  MASTER_CONNECT_RETRY&#x3D;10;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li>从库开启复制线程：start  slave;</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; show slave status \G;
--- 两个yes 就是成功
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="3-主从复制过程原理"><a href="#3-主从复制过程原理" class="headerlink" title="3.主从复制过程原理"></a>3.主从复制过程原理</h5><h6 id="3-1-涉及到的文件"><a href="#3-1-涉及到的文件" class="headerlink" title="3.1 涉及到的文件"></a>3.1 涉及到的文件</h6><ul>
<li>主库：binlog  </li>
<li>从库：<ul>
<li>relaylog 中继日志：存储请求的binlog    </li>
<li>master.info ：存储change master to 信息</li>
<li>relaylog.info：上次已经回放relay的位置点</li>
</ul>
</li>
</ul>
<h6 id="3-2-涉及到的线程"><a href="#3-2-涉及到的线程" class="headerlink" title="3.2 涉及到的线程"></a>3.2 涉及到的线程</h6><ul>
<li>主库<ul>
<li>binlog dump thread<pre class="line-numbers language-none"><code class="language-none">mysql&gt; show processlist\G;
*************************** 1. row ***************************
     Id: 6
   User: repl
   Host: db01:55196
     db: NULL
Command: Binlog Dump
   Time: 10015
  State: Master has sent all binlog to slave; waiting for more updates
   Info: NULL<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
</ul>
</li>
<li>从库 ：<ul>
<li>slave_io_running</li>
<li>slave_sql_running</li>
</ul>
</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[root@db01 ~]# mysql -S &#x2F;data&#x2F;3308&#x2F;mysql.sock -e &quot;show slave status \G&quot;|grep Running;
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h6 id="3-3工作过程原理："><a href="#3-3工作过程原理：" class="headerlink" title="3.3工作过程原理："></a>3.3工作过程原理：</h6><ul>
<li>change master to 时，ip port user password binlog position写入到master.info进行记录</li>
<li>start slave 时，从库会启动IO线程和SQL线程</li>
<li>IO_T，读取master.info信息，获取主库信息连接主库</li>
<li>主库会生成一个准备binlog DUMP线程，来响应从库</li>
<li>IO_T根据master.info记录的binlog文件名和position号，请求主库DUMP最新日志</li>
<li>DUMP线程检查主库的binlog日志，如果有新的，TP(传送)给从从库的IO_T</li>
<li>IO_T将收到的日志存储到了TCP&#x2F;IP 缓存，立即返回ACK(网络层面)给主库 ，主库工作完成</li>
<li>IO_T将缓存中的数据，存储到relay-log日志文件,更新master.info文件binlog 文件名和postion，IO_T工作完成</li>
<li>SQL_T读取relay-log.info文件，获取到上次执行到的relay-log的位置，作为起点，回放relay-log</li>
<li>SQL_T回放完成之后，会更新relay-log.info文件。</li>
<li>relay-log会有自动清理的功能。<br> <img src="https://img-blog.csdnimg.cn/343ba10293484586a6c435a6a36b25c3.png" alt="在这里插入图片描述"></li>
</ul>
<p>  细节：</p>
<ul>
<li>主库一旦有新的日志生成，会发送“信号”给binlog dump ，IO线程再请求</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[root@db01 world]# cd &#x2F;data&#x2F;3308&#x2F;data&#x2F;
[root@db01 data]# ll
total 122940
-rw-r----- 1 mysql mysql       56 Sep  3 15:18 auto.cnf
-rw-r----- 1 mysql mysql        6 Sep 16 12:19 db01.pid
-rw-r----- 1 mysql mysql      206 Sep 16 12:28 db01-relay-bin.000001
-rw-r----- 1 mysql mysql      320 Sep 16 12:28 db01-relay-bin.000002
-rw-r----- 1 mysql mysql       48 Sep 16 12:28 db01-relay-bin.index
drwxr-x--- 2 mysql mysql       20 Sep 16 12:23 ha
-rw-r----- 1 mysql mysql      359 Sep 16 10:13 ib_buffer_pool
-rw-r----- 1 mysql mysql 12582912 Sep 16 12:24 ibdata1
-rw-r----- 1 mysql mysql 50331648 Sep 16 12:24 ib_logfile0
-rw-r----- 1 mysql mysql 50331648 Sep 16 12:24 ib_logfile1
-rw-r----- 1 mysql mysql 12582912 Sep 16 12:19 ibtmp1
-rw-r----- 1 mysql mysql      122 Sep 16 15:52 master.info
drwxr-x--- 2 mysql mysql       48 Sep 16 12:23 mdp
drwxr-x--- 2 mysql mysql     4096 Sep 16 12:23 mysql
drwxr-x--- 2 mysql mysql       54 Sep 16 12:23 oldboy
drwxr-x--- 2 mysql mysql     8192 Sep  3 15:18 performance_schema
-rw-r----- 1 mysql mysql       58 Sep 16 12:28 relay-log.info
drwxr-x--- 2 mysql mysql       20 Sep 16 12:23 sch
drwxr-x--- 2 mysql mysql      176 Sep 16 12:23 school
drwxr-x--- 2 mysql mysql     8192 Sep  3 15:18 sys
drwxr-x--- 2 mysql mysql       52 Sep 16 12:23 test
drwxr-x--- 2 mysql mysql      246 Sep 16 12:23 world
drwxr-x--- 2 mysql mysql       46 Sep 16 12:23 x<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>从库可以查看日志：master.info</p>
<pre class="line-numbers language-none"><code class="language-none">[root@db01 data]# cat master.info 
25
mysql-bin.000002
444
10.0.0.51
repl
123456
3307
10
0





0
30.000

0
031e1ee9-ce1b-11e9-8e51-000c29303796
86400


0

<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="4-主从复制监控"><a href="#4-主从复制监控" class="headerlink" title="4.主从复制监控"></a>4.主从复制监控</h5><pre class="line-numbers language-none"><code class="language-none">mysql&gt; show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.0.51
                  Master_User: repl
                  Master_Port: 3307
                Connect_Retry: 10
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 444
               Relay_Log_File: db01-relay-bin.000002
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 444
              Relay_Log_Space: 526
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 7
                  Master_UUID: 031e1ee9-ce1b-11e9-8e51-000c29303796
             Master_Info_File: &#x2F;data&#x2F;3308&#x2F;data&#x2F;master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="4-1主库相关信息"><a href="#4-1主库相关信息" class="headerlink" title="4.1主库相关信息"></a>4.1主库相关信息</h6><pre class="line-numbers language-none"><code class="language-none">Master_Host: 10.0.0.51
Master_User: repl
Master_Port: 3307
Connect_Retry: 10
Master_Log_File: mysql-bin.000002
Read_Master_Log_Pos: 444<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="4-2-从库relaylog-的信息（relay-log-info）从库的320对应主库的444"><a href="#4-2-从库relaylog-的信息（relay-log-info）从库的320对应主库的444" class="headerlink" title="4.2  从库relaylog 的信息（relay-log.info）从库的320对应主库的444"></a>4.2  从库relaylog 的信息（relay-log.info）从库的320对应主库的444</h6><pre class="line-numbers language-none"><code class="language-none">Relay_Log_File: db01-relay-bin.000002
Relay_Log_Pos: 320
Relay_Master_Log_File: mysql-bin.000002
Exec_Master_Log_Pos: 444<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="4-3-线程状态："><a href="#4-3-线程状态：" class="headerlink" title="4.3 线程状态："></a>4.3 线程状态：</h6><pre class="line-numbers language-none"><code class="language-none">Slave_IO_Running: Yes
Slave_SQL_Running: Yes
--- 如果上面线程启动失败，则看下面的参数
Last_IO_Errno: 0
Last_IO_Error: 
Last_SQL_Errno: 0
Last_SQL_Error: <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>或者：<br>从库日志（log_error）线程启动no，但是没有报错信息可以查看</p>
<h6 id="4-4-过滤复制有关信息"><a href="#4-4-过滤复制有关信息" class="headerlink" title="4.4 过滤复制有关信息"></a>4.4 过滤复制有关信息</h6><pre class="line-numbers language-none"><code class="language-none">Replicate_Do_DB: 
Replicate_Ignore_DB: 
Replicate_Do_Table: 
Replicate_Ignore_Table: 
Replicate_Wild_Do_Table: 
Replicate_Wild_Ignore_Table: <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="4-5-从库延时主库的时间"><a href="#4-5-从库延时主库的时间" class="headerlink" title="4.5 从库延时主库的时间"></a>4.5 从库延时主库的时间</h6><pre class="line-numbers language-none"><code class="language-none">Seconds_Behind_Master: 0<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h6 id="4-6-延时从库（可以手动定制）"><a href="#4-6-延时从库（可以手动定制）" class="headerlink" title="4.6 延时从库（可以手动定制）"></a>4.6 延时从库（可以手动定制）</h6><pre class="line-numbers language-none"><code class="language-none">SQL_Delay: 0
SQL_Remaining_Delay: NULL<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h6 id="4-7-GTID-复制状态"><a href="#4-7-GTID-复制状态" class="headerlink" title="4.7 GTID 复制状态"></a>4.7 GTID 复制状态</h6><pre class="line-numbers language-none"><code class="language-none">Retrieved_Gtid_Set: 
Executed_Gtid_Set: 
Auto_Position: 0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h5 id="5-主从复制故障"><a href="#5-主从复制故障" class="headerlink" title="5.主从复制故障"></a>5.主从复制故障</h5><h6 id="5-1-IO线程"><a href="#5-1-IO线程" class="headerlink" title="5.1 IO线程"></a>5.1 IO线程</h6><pre class="line-numbers language-none"><code class="language-none">Slave_IO_Running: Yes
Last_IO_Errno: 0
Last_IO_Error: <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>1）连接主库 connecting</p>
<ul>
<li>IP</li>
<li>port</li>
<li>password</li>
<li>网络</li>
<li>防火墙</li>
<li>主库没起<br>排查：<br><strong>1. 查看从库的master.info</strong></li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">[root@db01 data]# pwd
&#x2F;data&#x2F;3308&#x2F;data
[root@db01 data]# cat master.info 
25
mysql-bin.000002
444
10.0.0.51
repl
123456
3307
10
0





0
30.000

0
031e1ee9-ce1b-11e9-8e51-000c29303796
86400


0<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>使用以上信息手工连接，查看结果</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">[root@db01 ~]# mysql -urepl -p123 -h 10.0.0.52 -P3307
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2003 (HY000): Can&#39;t connect to MySQL server on &#39;10.0.0.52&#39; (113)
[root@db01 ~]# mysql -urepl -p123 -h 10.0.0.51 -P3301
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2003 (HY000): Can&#39;t connect to MySQL server on &#39;10.0.0.51&#39; (111)
[root@db01 ~]# mysql -urepl -p123 -h 10.0.0.51 -P3307
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2003 (HY000): Can&#39;t connect to MySQL server on &#39;10.0.0.51&#39; (111)
[root@db01 ~]# mysql -urepl -p1234 -h 10.0.0.51 -P3307
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user &#39;repl&#39;@&#39;db01&#39; (using password: YES)
[root@db01 ~]# mysql -urepla -p123 -h 10.0.0.51 -P3307
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user &#39;repla&#39;@&#39;db01&#39; (using password: YES)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>在从库处理：</p>
<blockquote>
<p>stop  slave all;<br>reset slave all<br>change master to..<br>start salve;<br>show salve status\G;</p>
</blockquote>
<p>2）请求binlog<br>起点错误<br>主库二进制日志破坏</p>
<pre class="line-numbers language-none"><code class="language-none">Got fatal error 1236 from master when reading data from binary log: &#39;log event entry exceeded max_allowed_packet; Increase max_allowed_packet on master; the first event &#39;mysql-bin.000005&#39; at 653, the last event read from &#39;&#x2F;data&#x2F;3307&#x2F;mysql-bin.000005&#39; at 123, the last byte read from &#39;&#x2F;data&#x2F;3307&#x2F;mysql-bin.000005&#39; at 672.&#39;
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>3）记录日志</p>
<h6 id="5-2-SQL线程"><a href="#5-2-SQL线程" class="headerlink" title="5.2 SQL线程"></a>5.2 SQL线程</h6><p>回放Relaylog（binlog）：SQL回放不了</p>
<blockquote>
<p>SQL语句为什么会执行失败？<br>语法，sql_mode,<br>权限<br>创建的对象已经存在<br>从库创建一个库，然后在主库在创建一个库，就会报sql线程错误，需要把从库的库删除之后重新start slave;<br>修改或删除的对象不存在<br>约束冲突<br>数据类型<br>死锁<br>锁等待超时<br>命令失效<br>总结：<br>版本不一致<br>从库写入数据了：只读，读写分离中间件<br>手工补偿<br>pt-checksume<br>pt-sync</p>
</blockquote>
<pre class="line-numbers language-none"><code class="language-none">方法一：
stop slave; 
set global sql_slave_skip_counter &#x3D; 1;
#将同步指针向下移动一个，如果多次不同步，可以重复操作。
start slave;
方法二：
&#x2F;etc&#x2F;my.cnf
slave-skip-errors &#x3D; 1032,1062,1007
常见错误代码:
1007:对象已存在
1032:无法执行DML
1062:主键冲突,或约束冲突

但是，以上操作有时是有风险的，最安全的做法就是重新构建主从。把握一个原则,一切以主库为主.<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="6-主从延时"><a href="#6-主从延时" class="headerlink" title="6.主从延时"></a>6.主从延时</h5><h5 id="6-1-基础监控"><a href="#6-1-基础监控" class="headerlink" title="6.1 基础监控"></a>6.1 基础监控</h5><pre class="line-numbers language-none"><code class="language-none">Seconds_Behind_Master:0<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h5 id="6-2-日志量监控"><a href="#6-2-日志量监控" class="headerlink" title="6.2 日志量监控"></a>6.2 日志量监控</h5><p>1）主库</p>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; show master status\G;
*************************** 1. row ***************************
             File: mysql-bin.000008
         Position: 750
     Binlog_Do_DB: 
 Binlog_Ignore_DB: 
Executed_Gtid_Set: 1e91fb5a-cd38-11e9-b843-000c29303796:1-6,
b3ad910d-d832-11e9-89dc-000c29303796:1-2,
f66f1a5b-d827-11e9-bdf6-000c29303796:1-6
1 row in set (0.00 sec)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>2）从库</p>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; show salve status \G;
Master_Log_File: mysql-bin.000002
Read_Master_Log_Pos: 444<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-none"><code class="language-none">[root@db01 ~]# cat &#x2F;data&#x2F;3308&#x2F;data&#x2F;relay-log.info 
7
.&#x2F;db01-relay-bin.000002
320
mysql-bin.000002
444<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="6-3-导致主从延时的原因"><a href="#6-3-导致主从延时的原因" class="headerlink" title="6.3 导致主从延时的原因"></a>6.3 导致主从延时的原因</h6><p><strong>主库：</strong></p>
<ul>
<li>sync_binlog&#x3D;1</li>
<li>binlog存储性能低，建议换成SSD</li>
<li>binlog_dump 5.6以前的传统复制模型下，是串行工作的，如果在主库发生高并发事务，或者大事务的时候传输的时候，传输日志会受到阻塞。</li>
<li>早期解决办法，切割大事务。</li>
<li>5.6以后有了GTID模式，可以自动进行并行传输日志到从库</li>
<li>5.7以后即使不开启GTID模式也会有匿名的GTID，建议开启</li>
</ul>
<p><strong>从库：</strong></p>
<ul>
<li>从库SQL线程串行回放，在主库发生高并发事务，大事务的时候，会出现很高延时</li>
<li>在5.6中，开启GTID之后，使用多SQL线程并行回放，限制：只能针对database级别（不能多个线程同时回放一个库）实现并行</li>
<li>在5.7当中，开启GTID 之后，多SQL 并行回放，基于Logic_clock 实现了真正的事务级别的并行回放，这个技术称为MTS</li>
</ul>
<p>其他：</p>
<ul>
<li>网络</li>
<li>硬件差异大</li>
<li>版本</li>
<li>优化参数不一样</li>
<li>锁等待</li>
<li>死锁</li>
<li>从库太多</li>
<li>从库有大量的慢查询</li>
</ul>
<h5 id="7-延时从库"><a href="#7-延时从库" class="headerlink" title="7. 延时从库"></a>7. 延时从库</h5><h6 id="7-1-为什么要延时从库"><a href="#7-1-为什么要延时从库" class="headerlink" title="7.1 为什么要延时从库"></a>7.1 为什么要延时从库</h6><pre class="line-numbers language-none"><code class="language-none">数据库故障?
物理损坏
主从复制非常擅长解决物理损坏.
逻辑损坏
普通主从复制没办法解决逻辑损坏<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="7-2-配置"><a href="#7-2-配置" class="headerlink" title="7.2 配置"></a>7.2 配置</h6><pre class="line-numbers language-none"><code class="language-none">SQL线程延时:数据已经写入relaylog中了,SQL线程&quot;慢点&quot;运行
一般企业建议3-6小时,具体看公司运维人员对于故障的反应时间
mysql&gt;stop slave;
mysql&gt;CHANGE MASTER TO MASTER_DELAY &#x3D; 300;
mysql&gt;start slave;
mysql&gt; show slave status \G
SQL_Delay: 300
SQL_Remaining_Delay: NULL<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="7-3-如果使用延时从库恢复数据"><a href="#7-3-如果使用延时从库恢复数据" class="headerlink" title="7.3 如果使用延时从库恢复数据"></a>7.3 如果使用延时从库恢复数据</h6><p>测试演练：<br>1）背景：</p>
<ul>
<li>核心业务库</li>
<li>2T 数据 </li>
<li>主从复制  1主3从，主库负责写，两个从库负责读1，1 从库延时3小时<br>2）故障：</li>
<li>主库误删除了其中一个核心业务库，大约1T数据，（DROP DATABASE）<br>3）思路：</li>
<li>1.快速监控到故障</li>
<li>2.停业务，挂维护页</li>
<li>3.停延时从库</li>
<li>4.手工模拟SQL线程（截取日志）<ul>
<li>起点：relay.info</li>
<li>终点：drop之前<br>4）模拟过程<br>主库模拟数据</li>
</ul>
</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">--- 主库添加数据，模拟删除
create database delay charset utf8mb4;
use delay;
create table t1 (id int);
insert into t1 values(1),(2),(3);
commit;
insert into t1 values(11),(22),(33);
commit;
insert into t1 values(111),(222),(333);
commit;
drop database delay;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-none"><code class="language-none">--- 从库停止sql线程
mysql&gt; stop slave sql_thread;
Query OK, 0 rows affected (0.00 sec)
mysql&gt; show slave status \G;
起点：
Relay_Log_File: db01-relay-bin.000002
Relay_Log_Pos: 320
终点：
mysql&gt; show relaylog events in &#39;db01-relay-bin.000002&#39;;
| db01-relay-bin.000002 | 1523 | Query          |         7 |        1452 | drop database delay                 <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>截取relaylog</p>
<pre class="line-numbers language-none"><code class="language-none">[root@db01 ~]# mysqlbinlog --start-position&#x3D;320 --stop-position&#x3D;1523 &#x2F;data&#x2F;3308&#x2F;data&#x2F;db01-relay-bin.000002 &gt;&#x2F;tmp&#x2F;relay.sql<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>恢复relaylog</p>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; set sql_log_bin&#x3D;0;
mysql&gt; source &#x2F;tmp&#x2F;relay.sql
mysql&gt; use delay;
mysql&gt; show tables;
+-----------------+
| Tables_in_delay |
+-----------------+
| t1              |
+-----------------+
1 row in set (0.00 sec)

mysql&gt; select *from t1;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|   11 |
|   22 |
|   33 |
|  111 |
|  222 |
|  333 |
+------+
9 rows in set (0.00 sec)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="8-过滤复制"><a href="#8-过滤复制" class="headerlink" title="8.过滤复制"></a>8.过滤复制</h5><h6 id="8-1-配置"><a href="#8-1-配置" class="headerlink" title="8.1 配置"></a>8.1 配置</h6><p>主库：</p>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; show master status;
--- 白名单
Binlog_Do_DB
--- 黑名单
Binlog_Ignore_DB<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>从库：</p>
<pre class="line-numbers language-none"><code class="language-none">--- 白名单，只复制什么库
Replicate_Do_DB: 
--- 黑名单 ，不复制什么库
Replicate_Ignore_DB: 

--- 只复制什么表
Replicate_Do_Table: 
--- 不复制什么表
Replicate_Ignore_Table: 

---模糊
Replicate_Wild_Do_Table: 
Replicate_Wild_Ignore_Table: <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<pre class="line-numbers language-none"><code class="language-none">my.cnf
replicate_do_db&#x3D;world
replicate_do_table&#x3D;oldboy.t1
replicate_wild_do_table&#x3D;oldboy.t*<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>清理环境恢复主从</p>
<p>从库：</p>
<pre class="line-numbers language-none"><code class="language-none">stop  salve;
reset slave all;
drop database delay;
reset master;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>主库：</p>
<pre class="line-numbers language-none"><code class="language-none">reset master;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>从库：</p>
<pre class="line-numbers language-none"><code class="language-none">CHANGE MASTER TO
  MASTER_HOST&#x3D;&#39;10.0.0.51&#39;,
  MASTER_USER&#x3D;&#39;repl&#39;,
  MASTER_PASSWORD&#x3D;&#39;123456&#39;,
  MASTER_PORT&#x3D;3307,
  MASTER_LOG_FILE&#x3D;&#39;mysql-bin.000001&#39;,
  MASTER_LOG_POS&#x3D;154,
  MASTER_CONNECT_RETRY&#x3D;10;
start slave;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>配置：<br>从库：<br>添加白名单，设置白名单库，重启从库</p>
<pre class="line-numbers language-none"><code class="language-none">change master to master_host&#x3D;&#39;10.0.0.62&#39;,master_user&#x3D;&#39;repl&#39;,master_password&#x3D;&#39;123456&#39;,master_log_file&#x3D;&#39;mysql-bin.000002&#39;,master_log_pos&#x3D;154;
[root@db01 ~]# vim &#x2F;data&#x2F;3308&#x2F;my.cnf 
[mysqld]
basedir&#x3D;&#x2F;usr&#x2F;local&#x2F;mysql
datadir&#x3D;&#x2F;data&#x2F;3308&#x2F;data
socket&#x3D;&#x2F;data&#x2F;3308&#x2F;mysql.sock
log_error&#x3D;&#x2F;data&#x2F;3308&#x2F;mysql.log
port&#x3D;3308
server_id&#x3D;8
log_bin&#x3D;&#x2F;data&#x2F;3308&#x2F;mysql-bin
replicate_do_db&#x3D;oldboy
replicate_do_db&#x3D;school
[root@db01 ~]# systemctl restart mysqld3308<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>查看从库状态，白名单已经存在</p>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; show slave status\G;
Replicate_Do_DB: oldboy,school<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>主库：<br>创建一个新库，去从库查看库是否能创建</p>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; create database aaaa;<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>从库：<br>可以看到从库并没有创建aaaa库</p>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| ha                 |
| mdp                |
| mysql              |
| oldboy             |
| performance_schema |
| sch                |
| school             |
| sys                |
| test               |
| world              |
| x                  |
+--------------------+
12 rows in set (0.00 sec)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>主库：<br>在设置的白名单的库中添加一个表</p>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; use oldboy;
mysql&gt; show tables;
+------------------+
| Tables_in_oldboy |
+------------------+
| t100w            |
+------------------+
1 row in set (0.00 sec)
mysql&gt; create table t1(id int);
Query OK, 0 rows affected (0.01 sec)

mysql&gt; show tables;
+------------------+
| Tables_in_oldboy |
+------------------+
| t1               |
| t100w            |
+------------------+
2 rows in set (0.00 sec)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>从库：<br>查看从库中已经创建成功</p>
<pre class="line-numbers language-none"><code class="language-none">mysql&gt; show tables;
+------------------+
| Tables_in_oldboy |
+------------------+
| t1               |
| t100w            |
+------------------+
2 rows in set (0.00 sec)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="9-GTID复制"><a href="#9-GTID复制" class="headerlink" title="9.GTID复制"></a>9.GTID复制</h5><h6 id="9-1-3台虚拟机测试环境清理重构"><a href="#9-1-3台虚拟机测试环境清理重构" class="headerlink" title="9.1  3台虚拟机测试环境清理重构"></a>9.1  3台虚拟机测试环境清理重构</h6><pre class="line-numbers language-none"><code class="language-none">pkill mysqld
 \rm -rf &#x2F;data&#x2F;mysql&#x2F;data&#x2F;*
 \rm -rf &#x2F;data&#x2F;binlog&#x2F;*<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h5 id="9-2-准备配置文件"><a href="#9-2-准备配置文件" class="headerlink" title="9.2 准备配置文件"></a>9.2 准备配置文件</h5><pre class="line-numbers language-none"><code class="language-none">主库db01：
cat &gt; &#x2F;etc&#x2F;my.cnf &lt;&lt;EOF
[mysqld]
basedir&#x3D;&#x2F;usr&#x2F;local&#x2F;mysql&#x2F;
datadir&#x3D;&#x2F;data&#x2F;mysql&#x2F;data
socket&#x3D;&#x2F;tmp&#x2F;mysql.sock
server_id&#x3D;51
port&#x3D;3306
secure-file-priv&#x3D;&#x2F;tmp
autocommit&#x3D;0
log_bin&#x3D;&#x2F;data&#x2F;binlog&#x2F;mysql-bin
binlog_format&#x3D;row
gtid-mode&#x3D;on
enforce-gtid-consistency&#x3D;true
log-slave-updates&#x3D;1
[mysql]
prompt&#x3D;db01 [\\d]&gt;
EOF

slave1(db02)：
cat &gt; &#x2F;etc&#x2F;my.cnf &lt;&lt;EOF
[mysqld]
basedir&#x3D;&#x2F;usr&#x2F;local&#x2F;mysql
datadir&#x3D;&#x2F;data&#x2F;mysql&#x2F;data
socket&#x3D;&#x2F;tmp&#x2F;mysql.sock
server_id&#x3D;52
port&#x3D;3306
secure-file-priv&#x3D;&#x2F;tmp
autocommit&#x3D;0
log_bin&#x3D;&#x2F;data&#x2F;binlog&#x2F;mysql-bin
binlog_format&#x3D;row
gtid-mode&#x3D;on
enforce-gtid-consistency&#x3D;true
log-slave-updates&#x3D;1
[mysql]
prompt&#x3D;db02 [\\d]&gt;
EOF

slave2(db03)：
cat &gt; &#x2F;etc&#x2F;my.cnf &lt;&lt;EOF
[mysqld]
basedir&#x3D;&#x2F;usr&#x2F;local&#x2F;mysql
datadir&#x3D;&#x2F;data&#x2F;mysql&#x2F;data
socket&#x3D;&#x2F;tmp&#x2F;mysql.sock
server_id&#x3D;53
port&#x3D;3306
secure-file-priv&#x3D;&#x2F;tmp
autocommit&#x3D;0
log_bin&#x3D;&#x2F;data&#x2F;binlog&#x2F;mysql-bin
binlog_format&#x3D;row
gtid-mode&#x3D;on
enforce-gtid-consistency&#x3D;true
log-slave-updates&#x3D;1
[mysql]
prompt&#x3D;db03 [\\d]&gt;
EOF<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="9-3-初始化数据"><a href="#9-3-初始化数据" class="headerlink" title="9.3 初始化数据"></a>9.3 初始化数据</h6><pre class="line-numbers language-none"><code class="language-none">mysqld --initialize-insecure --user&#x3D;mysql --basedir&#x3D;&#x2F;usr&#x2F;local&#x2F;mysql --datadir&#x3D;&#x2F;data&#x2F;mysql&#x2F;data 
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h6 id="9-4-主库导入测试数据"><a href="#9-4-主库导入测试数据" class="headerlink" title="9.4 主库导入测试数据"></a>9.4 主库导入测试数据</h6><pre class="line-numbers language-none"><code class="language-none">source &#x2F;root&#x2F;world.sql<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h6 id="9-5-启动数据库"><a href="#9-5-启动数据库" class="headerlink" title="9.5 启动数据库"></a>9.5 启动数据库</h6><pre class="line-numbers language-none"><code class="language-none">&#x2F;etc&#x2F;init.d&#x2F;mysqld start<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h6 id="9-6-构建主从"><a href="#9-6-构建主从" class="headerlink" title="9.6 构建主从"></a>9.6 构建主从</h6><pre class="line-numbers language-none"><code class="language-none">master:51
slave:52,53<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>主：</p>
<pre class="line-numbers language-none"><code class="language-none">grant replication slave  on *.* to repl@&#39;10.0.0.%&#39; identified by &#39;123&#39;;
mysqldump  -A --master-data&#x3D;2 --single-transaction &gt;&#x2F;tmp&#x2F;full.sql<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>从：</p>
<pre class="line-numbers language-none"><code class="language-none">source &#x2F;tmp&#x2F;full.sql

change master to 
master_host&#x3D;&#39;10.0.0.51&#39;,
master_user&#x3D;&#39;repl&#39;,
master_password&#x3D;&#39;123&#39; ,
MASTER_AUTO_POSITION&#x3D;1;
start slave;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>主从复制不能添加 –set-gtid-purged&#x3D;OFF 参数<br>mysqldump -A –master-data&#x3D;2 –single-transaction –set-gtid-purged&#x3D;OFF &gt;&#x2F;tmp&#x2F;full2.sql</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love">J.</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love/2019/03/23/MySQL%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%EF%BC%88Replication%EF%BC%89/">http://dycloudnavite.love/2019/03/23/MySQL%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%EF%BC%88Replication%EF%BC%89/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://dycloudnavite.love" target="_blank">J.のblog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/dujie5416/tags/mysql/">mysql</a></div><div class="post_share"><div class="addthis_inline_share_toolbox"></div><script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5d034d84b42927bf" async="async"></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/dujie5416/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/dujie5416/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/dujie5416/2019/03/24/MySQL%20%E4%BC%98%E5%8C%96/"><img class="prev-cover" src="/dujie5416/img/mysql.jpg" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">MySQL 优化</div></div></a></div><div class="next-post pull-right"><a href="/dujie5416/2019/03/19/MySQL%20%E5%A4%87%E4%BB%BD%E6%81%A2%E5%A4%8D%EF%BC%88mysqldump%EF%BC%89/"><img class="next-cover" src="/dujie5416/img/mysql.jpg" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">MySQL 备份恢复(mysqldump)</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/dujie5416/2019/03/24/MySQL%20MHA%20%E9%AB%98%E5%8F%AF%E7%94%A8/" title="MySQL MHA 高可用"><img class="cover" src="/dujie5416/img/mysql.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-03-24</div><div class="title">MySQL MHA 高可用</div></div></a></div><div><a href="/dujie5416/2019/03/24/MySQL%20%E4%BC%98%E5%8C%96/" title="MySQL 优化"><img class="cover" src="/dujie5416/img/mysql.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-03-24</div><div class="title">MySQL 优化</div></div></a></div><div><a href="/dujie5416/2019/03/26/MySQL%20%E6%97%A5%E5%BF%97%E7%AE%A1%E7%90%86/" title="MySQL 日志管理"><img class="cover" src="/dujie5416/img/mysql.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-03-26</div><div class="title">MySQL 日志管理</div></div></a></div><div><a href="/dujie5416/2019/03/19/MySQL%20%E5%A4%87%E4%BB%BD%E6%81%A2%E5%A4%8D%EF%BC%88mysqldump%EF%BC%89/" title="MySQL 备份恢复(mysqldump)"><img class="cover" src="/dujie5416/img/mysql.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-03-19</div><div class="title">MySQL 备份恢复(mysqldump)</div></div></a></div><div><a href="/dujie5416/2019/03/08/MySQL%E5%88%86%E5%B8%83%E5%BC%8F%E6%9E%B6%E6%9E%84-MyCAT/" title="MySQL分布式架构-MyCAT"><img class="cover" src="/dujie5416/img/mysql.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-03-08</div><div class="title">MySQL分布式架构-MyCAT</div></div></a></div><div><a href="/dujie5416/2019/03/14/MySQL%E7%89%A9%E7%90%86%E5%A4%87%E4%BB%BD%E5%B7%A5%E5%85%B7%E4%BD%BF%E7%94%A8%EF%BC%88Percona%20Xtrabackup%EF%BC%89PBK%20%20%20XBK/" title="MySQL物理备份工具使用（Percona Xtrabackup）"><img class="cover" src="/dujie5416/img/mysql.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-03-14</div><div class="title">MySQL物理备份工具使用（Percona Xtrabackup）</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81Njk5OS8zMzQ2Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/dujie5416/img/touxiang.png" onerror="this.onerror=null;this.src='/dujie5416/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">J.</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6"><span class="toc-number">1.</span> <span class="toc-text">一、主从复制</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%E4%BB%8B%E7%BB%8D"><span class="toc-number">1.0.0.0.1.</span> <span class="toc-text">1.主从复制介绍</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%E6%90%AD%E5%BB%BA"><span class="toc-number">1.0.0.0.2.</span> <span class="toc-text">2.主从复制搭建</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%E8%BF%87%E7%A8%8B%E5%8E%9F%E7%90%86"><span class="toc-number">1.0.0.0.3.</span> <span class="toc-text">3.主从复制过程原理</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#3-1-%E6%B6%89%E5%8F%8A%E5%88%B0%E7%9A%84%E6%96%87%E4%BB%B6"><span class="toc-number">1.0.0.0.3.1.</span> <span class="toc-text">3.1 涉及到的文件</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#3-2-%E6%B6%89%E5%8F%8A%E5%88%B0%E7%9A%84%E7%BA%BF%E7%A8%8B"><span class="toc-number">1.0.0.0.3.2.</span> <span class="toc-text">3.2 涉及到的线程</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#3-3%E5%B7%A5%E4%BD%9C%E8%BF%87%E7%A8%8B%E5%8E%9F%E7%90%86%EF%BC%9A"><span class="toc-number">1.0.0.0.3.3.</span> <span class="toc-text">3.3工作过程原理：</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#4-%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%E7%9B%91%E6%8E%A7"><span class="toc-number">1.0.0.0.4.</span> <span class="toc-text">4.主从复制监控</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#4-1%E4%B8%BB%E5%BA%93%E7%9B%B8%E5%85%B3%E4%BF%A1%E6%81%AF"><span class="toc-number">1.0.0.0.4.1.</span> <span class="toc-text">4.1主库相关信息</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#4-2-%E4%BB%8E%E5%BA%93relaylog-%E7%9A%84%E4%BF%A1%E6%81%AF%EF%BC%88relay-log-info%EF%BC%89%E4%BB%8E%E5%BA%93%E7%9A%84320%E5%AF%B9%E5%BA%94%E4%B8%BB%E5%BA%93%E7%9A%84444"><span class="toc-number">1.0.0.0.4.2.</span> <span class="toc-text">4.2  从库relaylog 的信息（relay-log.info）从库的320对应主库的444</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#4-3-%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81%EF%BC%9A"><span class="toc-number">1.0.0.0.4.3.</span> <span class="toc-text">4.3 线程状态：</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#4-4-%E8%BF%87%E6%BB%A4%E5%A4%8D%E5%88%B6%E6%9C%89%E5%85%B3%E4%BF%A1%E6%81%AF"><span class="toc-number">1.0.0.0.4.4.</span> <span class="toc-text">4.4 过滤复制有关信息</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#4-5-%E4%BB%8E%E5%BA%93%E5%BB%B6%E6%97%B6%E4%B8%BB%E5%BA%93%E7%9A%84%E6%97%B6%E9%97%B4"><span class="toc-number">1.0.0.0.4.5.</span> <span class="toc-text">4.5 从库延时主库的时间</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#4-6-%E5%BB%B6%E6%97%B6%E4%BB%8E%E5%BA%93%EF%BC%88%E5%8F%AF%E4%BB%A5%E6%89%8B%E5%8A%A8%E5%AE%9A%E5%88%B6%EF%BC%89"><span class="toc-number">1.0.0.0.4.6.</span> <span class="toc-text">4.6 延时从库（可以手动定制）</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#4-7-GTID-%E5%A4%8D%E5%88%B6%E7%8A%B6%E6%80%81"><span class="toc-number">1.0.0.0.4.7.</span> <span class="toc-text">4.7 GTID 复制状态</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#5-%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6%E6%95%85%E9%9A%9C"><span class="toc-number">1.0.0.0.5.</span> <span class="toc-text">5.主从复制故障</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#5-1-IO%E7%BA%BF%E7%A8%8B"><span class="toc-number">1.0.0.0.5.1.</span> <span class="toc-text">5.1 IO线程</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#5-2-SQL%E7%BA%BF%E7%A8%8B"><span class="toc-number">1.0.0.0.5.2.</span> <span class="toc-text">5.2 SQL线程</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#6-%E4%B8%BB%E4%BB%8E%E5%BB%B6%E6%97%B6"><span class="toc-number">1.0.0.0.6.</span> <span class="toc-text">6.主从延时</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#6-1-%E5%9F%BA%E7%A1%80%E7%9B%91%E6%8E%A7"><span class="toc-number">1.0.0.0.7.</span> <span class="toc-text">6.1 基础监控</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#6-2-%E6%97%A5%E5%BF%97%E9%87%8F%E7%9B%91%E6%8E%A7"><span class="toc-number">1.0.0.0.8.</span> <span class="toc-text">6.2 日志量监控</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#6-3-%E5%AF%BC%E8%87%B4%E4%B8%BB%E4%BB%8E%E5%BB%B6%E6%97%B6%E7%9A%84%E5%8E%9F%E5%9B%A0"><span class="toc-number">1.0.0.0.8.1.</span> <span class="toc-text">6.3 导致主从延时的原因</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#7-%E5%BB%B6%E6%97%B6%E4%BB%8E%E5%BA%93"><span class="toc-number">1.0.0.0.9.</span> <span class="toc-text">7. 延时从库</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#7-1-%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E5%BB%B6%E6%97%B6%E4%BB%8E%E5%BA%93"><span class="toc-number">1.0.0.0.9.1.</span> <span class="toc-text">7.1 为什么要延时从库</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#7-2-%E9%85%8D%E7%BD%AE"><span class="toc-number">1.0.0.0.9.2.</span> <span class="toc-text">7.2 配置</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#7-3-%E5%A6%82%E6%9E%9C%E4%BD%BF%E7%94%A8%E5%BB%B6%E6%97%B6%E4%BB%8E%E5%BA%93%E6%81%A2%E5%A4%8D%E6%95%B0%E6%8D%AE"><span class="toc-number">1.0.0.0.9.3.</span> <span class="toc-text">7.3 如果使用延时从库恢复数据</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#8-%E8%BF%87%E6%BB%A4%E5%A4%8D%E5%88%B6"><span class="toc-number">1.0.0.0.10.</span> <span class="toc-text">8.过滤复制</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#8-1-%E9%85%8D%E7%BD%AE"><span class="toc-number">1.0.0.0.10.1.</span> <span class="toc-text">8.1 配置</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#9-GTID%E5%A4%8D%E5%88%B6"><span class="toc-number">1.0.0.0.11.</span> <span class="toc-text">9.GTID复制</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#9-1-3%E5%8F%B0%E8%99%9A%E6%8B%9F%E6%9C%BA%E6%B5%8B%E8%AF%95%E7%8E%AF%E5%A2%83%E6%B8%85%E7%90%86%E9%87%8D%E6%9E%84"><span class="toc-number">1.0.0.0.11.1.</span> <span class="toc-text">9.1  3台虚拟机测试环境清理重构</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#9-2-%E5%87%86%E5%A4%87%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-number">1.0.0.0.12.</span> <span class="toc-text">9.2 准备配置文件</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#9-3-%E5%88%9D%E5%A7%8B%E5%8C%96%E6%95%B0%E6%8D%AE"><span class="toc-number">1.0.0.0.12.1.</span> <span class="toc-text">9.3 初始化数据</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#9-4-%E4%B8%BB%E5%BA%93%E5%AF%BC%E5%85%A5%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE"><span class="toc-number">1.0.0.0.12.2.</span> <span class="toc-text">9.4 主库导入测试数据</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#9-5-%E5%90%AF%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="toc-number">1.0.0.0.12.3.</span> <span class="toc-text">9.5 启动数据库</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#9-6-%E6%9E%84%E5%BB%BA%E4%B8%BB%E4%BB%8E"><span class="toc-number">1.0.0.0.12.4.</span> <span class="toc-text">9.6 构建主从</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="vue3左侧菜单隐藏某选项"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项">vue3左侧菜单隐藏某选项</a><time datetime="2023-07-29T06:32:00.000Z" title="发表于 2023-07-29 14:32:00">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Vue状态管理"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理">Vue状态管理</a><time datetime="2023-07-13T09:29:00.000Z" title="发表于 2023-07-13 17:29:00">2023-07-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="基于IOC解决对象依赖问题"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题">基于IOC解决对象依赖问题</a><time datetime="2023-06-27T03:32:00.000Z" title="发表于 2023-06-27 11:32:00">2023-06-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Gin框架"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架">Gin框架</a><time datetime="2023-06-23T06:32:00.000Z" title="发表于 2023-06-23 14:32:00">2023-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="ServeMux、httprouter"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter">ServeMux、httprouter</a><time datetime="2023-06-04T03:32:00.000Z" title="发表于 2023-06-04 11:32:00">2023-06-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/dujie5416/img/longzhu.png')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2024  <i id="heartbeat" class="fa fas fa-heartbeat"></i> J.</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><a href="http://beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">京ICP备2022023567号</a></div></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><a class="rightMenu-item menu-link" id="menu-radompage" href="/random/index.html"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></a><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/dujie5416/js/utils.js"></script><script src="/dujie5416/js/main.js"></script><script src="/dujie5416/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/dujie5416/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !false) {
  if (false) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script data-pjax defer src="https://npm.elemecdn.com/tzy-blog/lib/js/theme/chocolate.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer data-pjax src="/js/rightMenu.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="I,LOVE,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    if(parent_div_git) {
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = '56289903f0d448dfbe8262dba0175f70';
  var gaud_map_key = '01603f2b2d08d0e947bb101e9d9b148b';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --><script src="/dujie5416/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"tagMode":false,"debug":false,"model":{"jsonPath":"/dujie5416/live2dw/assets/tororo.model.json"},"display":{"position":"right","width":150,"height":350,"hOffset":20,"vOffset":-20},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>